package com.newtouch.avmarketing.mgr.modules.avmarkrting.service.impl;

import com.newtouch.avmarketing.mgr.modules.avmarkrting.config.MyBeanUtils;
import com.newtouch.avmarketing.mgr.modules.avmarkrting.entity.ConfigurationContent;
import com.newtouch.avmarketing.mgr.modules.avmarkrting.entity.DoubleConfiguration;
import com.newtouch.avmarketing.mgr.modules.avmarkrting.entity.SpeechRule;
import com.newtouch.avmarketing.mgr.modules.avmarkrting.model.DoubleCondition;
import com.newtouch.avmarketing.mgr.modules.avmarkrting.model.DoubleConfigurationReq;
import com.newtouch.avmarketing.mgr.modules.avmarkrting.repo.ConfigurationContentRepo;
import com.newtouch.avmarketing.mgr.modules.avmarkrting.repo.DoubleConfigurationRepo;
import com.newtouch.avmarketing.mgr.modules.avmarkrting.repo.SpeechRuleRepo;
import com.newtouch.avmarketing.mgr.modules.avmarkrting.service.DoubleConfigurationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class DoubleConfigurationServiceImpl implements DoubleConfigurationService {
    @Autowired
    private DoubleConfigurationRepo doubleConfigurationRepo;
    @Autowired
    private ConfigurationContentRepo configurationContentRepo;
    @Autowired
    private SpeechRuleRepo speechRuleRepo;

    private Logger logger = LoggerFactory.getLogger(DoubleConfigurationService.class);

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveConfiguration(DoubleConfigurationReq doubleConfigurationReq) {
        try{
            doubleConfigurationReq.getDoubleConfiguration().setIsDeleted("0");//逻辑删除  1:已删除 0:未删除
            //话术规则添加
            if ("1".equals(doubleConfigurationReq.getDoubleConfiguration().getReportType())){//1.固定话术
                doubleConfigurationRepo.save(doubleConfigurationReq.getDoubleConfiguration());
            }else {
                doubleConfigurationRepo.save(doubleConfigurationReq.getDoubleConfiguration());//2.有条件话术
                //循环添加有条件话术内容
                for (int i = 0; i < doubleConfigurationReq.getConfigurationContent().size(); i++) {
                    ConfigurationContent configurationContent = new ConfigurationContent();

                    configurationContent.setStepId(doubleConfigurationReq.getDoubleConfiguration().getId());
                    configurationContent.setContent(doubleConfigurationReq.getConfigurationContent().get(i).getContent());
                    configurationContent.setConditions(doubleConfigurationReq.getConfigurationContent().get(i).getConditions());
                    configurationContent.setConditionContent(doubleConfigurationReq.getConfigurationContent().get(i).getConditionContent());
                    configurationContent.setIsDeleted("0");
                    configurationContentRepo.save(configurationContent);
                }
            }
            //播报规则添加
            if ("1".equals(doubleConfigurationReq.getDoubleConfiguration().getIsReport())){//1:固定播报  2:有则播报
                doubleConfigurationRepo.save(doubleConfigurationReq.getDoubleConfiguration());
            }else {
                doubleConfigurationRepo.save(doubleConfigurationReq.getDoubleConfiguration());
                for (int i = 0; i < doubleConfigurationReq.getSpeechRules().size(); i++) {
                    SpeechRule speechRule = new SpeechRule();

                    speechRule.setStepId(doubleConfigurationReq.getDoubleConfiguration().getId());
                    speechRule.setConditions(doubleConfigurationReq.getSpeechRules().get(i).getConditions());
                    speechRule.setConditionContent(doubleConfigurationReq.getSpeechRules().get(i).getConditionContent());
                    speechRule.setIsDeleted("0");

                    speechRuleRepo.save(speechRule);
                }
            }
            logger.info("双录配置新增成功！");
            return 1;
        }catch (Exception e){
            logger.error("双录配置新增出错！",e);
            return 0;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateConfigurationById(DoubleConfigurationReq doubleConfigurationReq) {
        try{
            //修改双录主配置信息
            DoubleConfiguration doubleConfiguration1 = doubleConfigurationRepo.findByIds(doubleConfigurationReq.getDoubleConfiguration().getId());
            BeanUtils.copyProperties(doubleConfigurationReq.getDoubleConfiguration(),
                    doubleConfiguration1, MyBeanUtils.getNullPropertyNames(doubleConfigurationReq.getDoubleConfiguration()));
            doubleConfigurationRepo.save(doubleConfiguration1);

            //循环修改有条件话术对象内容
            if (doubleConfigurationReq.getConfigurationContent().size()!=0){
                for (int i = 0; i < doubleConfigurationReq.getConfigurationContent().size(); i++) {
                    configurationContentRepo.saveAndFlush(doubleConfigurationReq.getConfigurationContent().get(i));
                }
            }else {
                logger.error("有条件话术对象为空，修改失败");
            }

            //循环修改播报规则对象内容
            if (doubleConfigurationReq.getSpeechRules().size()!=0){
                for (int i = 0; i < doubleConfigurationReq.getSpeechRules().size(); i++) {
                    speechRuleRepo.saveAndFlush(doubleConfigurationReq.getSpeechRules().get(i));
                }
            }else {
                logger.error("播报规则对象为空，修改失败");
            }
            logger.info("双录配置更新成功");
            return 1;
        }catch (Exception e){
            logger.error("双录配置更新出错！",e);
            return 0;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteConfiguration(Long stepId) {
        try{
            doubleConfigurationRepo.deleteConfigurationById(stepId);
            configurationContentRepo.deleteConfigurationContentByStepId(stepId);
            speechRuleRepo.deleteSpeechRuleByStepId(stepId);
            logger.info("双录配置删除成功");
            return 1;
        }catch (Exception e){
            logger.error("双录配置删除出错！",e);
            return 0;
        }
    }
    /**
     * 通过步骤序号查找双录步骤
     * @param id
     * @return
     */
    @Override
    public DoubleConfiguration findByIds(Long id) {
        return doubleConfigurationRepo.findByIds(id);
    }
    @Override
    public Page<DoubleConfiguration> findByStepNameContaining(DoubleCondition doubleCondition) {
        Specification<DoubleConfiguration> spec = new Specification<DoubleConfiguration>() {
            @Override
            public Predicate toPredicate(Root<DoubleConfiguration> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<>();
                //话术名称模糊搜索
                if (!StringUtils.isEmpty(doubleCondition.getStepName())) {
                    predicateList.add(cb.like(root.get("stepName"), "%" + doubleCondition.getStepName() + "%"));
                }
                //拼接 ”未删除” 字段  1：已删除  0：未删除
                predicateList.add(cb.equal(root.get("isDeleted"), "0"));
                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        Sort sort = new Sort(Sort.Direction.ASC, "id");
        Pageable pageable = PageRequest.of(doubleCondition.getPageNumber()-1,doubleCondition.getPageSize(),sort);
        Page<DoubleConfiguration> list = doubleConfigurationRepo.findAll(spec, pageable);

        return list;
    }
}

